// 自行车社区模型 - MongoDB
import { mongoDb } from '../../config/multi-database.js';

class BikeCommunity {
  // 添加产品评价
  static async addProductReview(reviewData) {
    try {
      const review = {
        product_id: reviewData.product_id,
        user_id: reviewData.user_id,
        rating: reviewData.rating,
        title: reviewData.title,
        content: reviewData.content,
        images: reviewData.images || [],
        tags: reviewData.tags || [],
        helpful_votes: 0,
        verified_purchase: reviewData.verified_purchase || false,
        created_at: new Date(),
        updated_at: new Date()
      };
      
      const result = await mongoDb.collection('product_reviews').insertOne(review);
      
      // 更新产品评分统计
      await this.updateProductRating(reviewData.product_id);
      
      return { ...review, _id: result.insertedId };
      
    } catch (error) {
      console.error('添加产品评价失败:', error);
      throw error;
    }
  }
  
  // 更新产品评分统计
  static async updateProductRating(productId) {
    try {
      const pipeline = [
        { $match: { product_id: productId } },
        {
          $group: {
            _id: '$product_id',
            average_rating: { $avg: '$rating' },
            total_reviews: { $sum: 1 },
            rating_distribution: {
              $push: '$rating'
            }
          }
        }
      ];
      
      const result = await mongoDb.collection('product_reviews').aggregate(pipeline).toArray();
      
      if (result.length > 0) {
        const stats = result[0];
        
        // 计算评分分布
        const distribution = { 1: 0, 2: 0, 3: 0, 4: 0, 5: 0 };
        stats.rating_distribution.forEach(rating => {
          distribution[rating] = (distribution[rating] || 0) + 1;
        });
        
        const ratingStats = {
          product_id: productId,
          average_rating: Math.round(stats.average_rating * 10) / 10,
          total_reviews: stats.total_reviews,
          rating_distribution: distribution,
          updated_at: new Date()
        };
        
        // 更新或插入评分统计
        await mongoDb.collection('product_ratings').updateOne(
          { product_id: productId },
          { $set: ratingStats },
          { upsert: true }
        );
        
        // 更新Redis缓存
        const { setCache, CACHE_PREFIX } = await import('../config/multi-database.js');
        await setCache(`${CACHE_PREFIX.PRODUCT}rating:${productId}`, ratingStats, 3600);
        
        return ratingStats;
      }
      
    } catch (error) {
      console.error('更新产品评分失败:', error);
    }
  }
  
  // 获取产品评价
  static async getProductReviews(productId, page = 1, limit = 10, sortBy = 'created_at') {
    try {
      const skip = (page - 1) * limit;
      
      const reviews = await mongoDb.collection('product_reviews')
        .find({ product_id: productId })
        .sort({ [sortBy]: -1 })
        .skip(skip)
        .limit(limit)
        .toArray();
      
      const total = await mongoDb.collection('product_reviews')
        .countDocuments({ product_id: productId });
      
      return {
        reviews,
        total,
        page,
        limit,
        totalPages: Math.ceil(total / limit)
      };
      
    } catch (error) {
      console.error('获取产品评价失败:', error);
      throw error;
    }
  }
  
  // 添加社区帖子
  static async addCommunityPost(postData) {
    try {
      const post = {
        title: postData.title,
        content: postData.content,
        author_id: postData.author_id,
        category: postData.category, // 'discussion', 'technical', 'review', 'news'
        tags: postData.tags || [],
        images: postData.images || [],
        likes: 0,
        comments: 0,
        views: 0,
        status: 'published',
        created_at: new Date(),
        updated_at: new Date()
      };
      
      const result = await mongoDb.collection('community_posts').insertOne(post);
      
      return { ...post, _id: result.insertedId };
      
    } catch (error) {
      console.error('添加社区帖子失败:', error);
      throw error;
    }
  }
  
  // 获取社区帖子列表
  static async getCommunityPosts(filters = {}, page = 1, limit = 20) {
    try {
      const skip = (page - 1) * limit;
      const query = { status: 'published' };
      
      if (filters.category) {
        query.category = filters.category;
      }
      
      if (filters.tags && filters.tags.length > 0) {
        query.tags = { $in: filters.tags };
      }
      
      if (filters.author_id) {
        query.author_id = filters.author_id;
      }
      
      const posts = await mongoDb.collection('community_posts')
        .find(query)
        .sort({ created_at: -1 })
        .skip(skip)
        .limit(limit)
        .toArray();
      
      const total = await mongoDb.collection('community_posts')
        .countDocuments(query);
      
      return {
        posts,
        total,
        page,
        limit,
        totalPages: Math.ceil(total / limit)
      };
      
    } catch (error) {
      console.error('获取社区帖子失败:', error);
      throw error;
    }
  }
  
  // 记录用户行为
  static async logUserBehavior(behaviorData) {
    try {
      const behavior = {
        user_id: behaviorData.user_id,
        action_type: behaviorData.action_type, // 'view_product', 'search', 'add_to_cart', 'purchase'
        target_id: behaviorData.target_id,
        target_type: behaviorData.target_type, // 'product', 'category', 'post'
        metadata: behaviorData.metadata || {},
        ip_address: behaviorData.ip_address,
        user_agent: behaviorData.user_agent,
        timestamp: new Date()
      };
      
      await mongoDb.collection('user_behavior').insertOne(behavior);
      
      // 更新实时统计（Redis）
      await this.updateRealTimeStats(behavior);
      
    } catch (error) {
      console.error('记录用户行为失败:', error);
    }
  }
  
  // 更新实时统计
  static async updateRealTimeStats(behavior) {
    try {
      const { redisClient } = await import('../config/multi-database.js');
      
      const today = new Date().toISOString().split('T')[0];
      
      // 今日总访问量
      await redisClient.hIncrBy('stats:daily_visits', today, 1);
      
      // 行为类型统计
      await redisClient.hIncrBy(`stats:behavior:${today}`, behavior.action_type, 1);
      
      // 热门产品访问
      if (behavior.target_type === 'product') {
        await redisClient.zIncrBy('stats:hot_products', 1, behavior.target_id);
      }
      
      // 在线用户数（5分钟过期）
      await redisClient.setEx(`user:online:${behavior.user_id}`, 300, 'active');
      
    } catch (error) {
      console.error('更新实时统计失败:', error);
    }
  }
  
  // 获取用户行为分析
  static async getUserBehaviorAnalysis(userId, days = 30) {
    try {
      const startDate = new Date();
      startDate.setDate(startDate.getDate() - days);
      
      const pipeline = [
        {
          $match: {
            user_id: userId,
            timestamp: { $gte: startDate }
          }
        },
        {
          $group: {
            _id: {
              action_type: '$action_type',
              date: { $dateToString: { format: '%Y-%m-%d', date: '$timestamp' } }
            },
            count: { $sum: 1 }
          }
        },
        {
          $group: {
            _id: '$_id.action_type',
            daily_stats: {
              $push: {
                date: '$_id.date',
                count: '$count'
              }
            },
            total_count: { $sum: '$count' }
          }
        }
      ];
      
      const result = await mongoDb.collection('user_behavior')
        .aggregate(pipeline)
        .toArray();
      
      return result;
      
    } catch (error) {
      console.error('获取用户行为分析失败:', error);
      throw error;
    }
  }
  
  // 搜索社区内容
  static async searchCommunityContent(query, filters = {}, page = 1, limit = 20) {
    try {
      const skip = (page - 1) * limit;
      
      const searchPipeline = [
        {
          $search: {
            index: 'community_content',
            text: {
              query: query,
              path: ['title', 'content', 'tags'],
              fuzzy: { maxEdits: 2 }
            }
          }
        },
        {
          $match: {
            status: 'published',
            ...filters
          }
        },
        {
          $project: {
            title: 1,
            content: { $substr: ['$content', 0, 200] },
            category: 1,
            tags: 1,
            likes: 1,
            comments: 1,
            created_at: 1,
            score: { $meta: 'searchScore' }
          }
        },
        { $skip: skip },
        { $limit: limit }
      ];
      
      const [posts, reviews] = await Promise.all([
        mongoDb.collection('community_posts').aggregate(searchPipeline).toArray(),
        mongoDb.collection('product_reviews').aggregate(searchPipeline).toArray()
      ]);
      
      // 合并结果并按相关性排序
      const results = [...posts, ...reviews]
        .sort((a, b) => b.score - a.score);
      
      return {
        results,
        page,
        limit,
        total: results.length
      };
      
    } catch (error) {
      console.error('搜索社区内容失败:', error);
      throw error;
    }
  }
}

export default BikeCommunity;